<?php
/**
 * 会员相关
 * @author fanzhanao
 *
 */
//error_reporting(E_ALL);
class member_controller_index extends SnsController{
	
	var $data = '';
	var $no_right = false;
	public function __construct($app, $controller){
		parent::__construct($app, $controller);
		$this->data	=	Model::factory('member_model_data');
		$this->cartoon = Model::factory('cartoon_model_data');
		$this->chapter = Model::factory('cartoon_model_chapter');
		$this->photo = Model::factory('cartoon_model_photo');
		$this->tag	=	Model::factory('cartoon_model_tag');
        $this->avatar = Model::factory('member_util_avatar');
	}
	
	public function reg_action(){
		$this->frameView = VIEW_PATH.'/index.phtml';
		$this->no_right = true;
		$this->view = 'reg';
	}
	
	
	public function index_action(){
		$uid = $this->uid;
		if(!$uid) {
			$this->requireLogin();
		}		
		$page = _('page',1);
		$pageSize = 8;
		$userinfo = member_util_login::getMemberInfo($uid);		
		$cartoonList = Model::factory('cartoon_model_data')->getCartoonList(array('uid'=>$uid));		
		$this->ret = array('userinfo' => $userinfo,'cartoonList'=>$cartoonList);
		$this->view = 'index';
	}
	
	/**
	 * 找回密码
	 *
	 */
	public function find_pwd_action(){
		$this->frameView = VIEW_PATH.'/index.phtml';
		$this->no_right = true;
		$this->view = 'reset_pwd';
	}
	
	/**
	 * 找密码
	 *
	 */
	public function get_pwd_action(){
		$email = _('email');
		$this->_renderJson();
		if(!checkEmail($email)){
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS );
			return;
		}
		$code = member_util_interface::enCode($email);	
		$subject = '仨爪漫画找回密码！';
		$content = '<h2>尊敬的仨爪漫画用户，您好！</h2><br /><p>&nbsp;&nbsp;&nbsp;&nbsp;您使用了找回密码功能，请点击下面的链接重置您的密码：</p>
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<p><a href="http://i.'.DOMAIN.'/~member.index.reset_pwd?code='.$code.'" target="_blank" >点击这里</a></p>
		<p>注意此链接将在24小时内失效。</p>';
		$rs = member_util_interface::sendMail($email,$subject,$content);
		if($rs){
			//发送邮件成功
			$this->data->addFindPwdLog($email);
			$this->ret = self::success($email);
			return ;
		}else{
			$this->ret = self::success(Error::ERROR_UNKNOWN );
			return ;
		}
	}
	
	/**
	 * 重置密码
	 *
	 */
	public function reset_pwd_action(){
		$code = _('code');
		if($code){
			$mail = member_util_interface::deCode($code);
			if (intval(CURRENT_TIME - intval($mail['expire']))>EXPIRE_PWD) {//过期了
				$this->ret = self::failure('<h2>您的重置密码链接已经过期，请重新使用找回密码功能</h2>');
			}else{
				$rs = $this->data->chkMail($mail['email']);
				if($rs['result']){
					$this->ret = self::success($rs['data']);
				}else{
					$msg = '<h2>数据错误或者已经超时!</h2>';
					if($rs['reson'] == Error::ERROR_EXPIRE ){
						$msg = '<h2>重置密码已经超时!，请重新使用找回密码功能</h2>';
					}
					$this->ret = self::failure($msg);
				}
			}
		}else{
			$this->ret = self::failure('<h2>参数错误!</h2>');
		}
		$this->frameView = VIEW_PATH.'/index.phtml';
		$this->no_right = true;
		$this->view = 'reset_pwd2';
	}
	/**
	 * 重置密码第二步
	 *
	 */
	public function reset_pwd2_action(){
		$this->_renderJson();
//		$this->requireLogin();
		if(!(checkEmail(_('email')) and trim(_('password')))){
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS );
			return ;
		}
		if(!($userinfo = $this->data->getUserByEmail(_('email')))){
			$this->ret = self::failure(Error::ERROR_NO_SUCH_USER);
			return ;
		}
		$args['pwd'] = member_util_interface::genKey($userinfo['username'],_('password'));	
		if($this->data->edit($args,$userinfo['uid'])){
			$this->data->delPwdLog(_('email'));
			$this->ret = self::success(_('email'));
			return;
		}
		$this->ret = self::failure(Error::ERROR_UNKNOWN );
	}
	
	/**
	 * 注册会员
	 *
	 */
	public function register_action(){
		$args['username'] = trim_str(_('nickname'));
		$args['email']	=	trim_str(_('email'));
		$args['pwd']	=	trim_str(_('password'));
		$this->_renderJson();
		$err = array();		
		$check = true;
		if(!$args['username']){
			array_push($err,array('src'=>'nickname','msg'=>'用户名不能为空！'));
			$check = false;
		}
		
		/**
		 * 判断用户名是否已经存在
		 */
		if($this->data->getUserByName($args['username'],array('uid'))){
			array_push($err,array('src'=>'nickname','msg'=>'用户名已经存在！'));
			$check = false;
		}
		if(!checkEmail($args['email'])){
			array_push($err,array('src'=>'email','msg'=>'邮箱格式不对，或者邮箱为空！或者邮箱已经被注册'));
			$check = false;
		}
		/**
		 * 判断邮箱是否已经被注册$pattern="/^([\w\.-]+)@([a-zA-Z0-9-]+)(\.[a-zA-Z\.]+)$/i"
		 */
		if($this->data->getUserByEmail($args['email'],array('uid'))){
			array_push($err,array('src'=>'email','msg'=>'邮箱已经被注册'));
			$check = false;
		}
		if(!trim_str($args['pwd'])){
			array_push($err,array('src'=>'password','msg'=>'密码不能为空'));
			$check = false;
		}
		/*if(vcode_get2(Cache::getInstance(), 'vcode')!=strtoupper(_('vcode'))){
			array_push($err,array('src'=>'vcode','msg'=>'验证码不对！'));
			$check = false;
		}else{
			Plugin::vcode_clean();
		}*/
		
		/**
		 * 注册会员信息
		 */
		
		if ($check) {
			if ($uid = $this->data->register ( $args )) {
				$this->ret = self::success ( $uid );
			}else{
				$this->ret = self::failure('注册失败！');
			}
		}else{
			$this->ret	=	self::failure($err);
		}
	}
	
	/**
	 * 账户相关信息修改
	 */
	public function account_action(){
		$this->requireLogin();
		$uid = self::$login['uid'];
		$info = $this->data->getUserByUid($uid);
		$this->ret = array('userinfo'=>$info);
        $this->view = 'setting';
	}
	
	/**
	 * 更新会员相关信息
	 *
	 */
	public function save_prop_action(){
		$this->_renderJson();

		if (!(self::$login && self::$login['uid'])) {
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
			return;
		}

		$uid = self::$login['uid'];
        
		$arguments = array();
		$arguments['birthday'] 		=   sprintf("%04d", _('year'))."-".sprintf("%02d", _('month'))."-".sprintf("%02d", _('day'));
		$arguments['sex']			=	_('gender_flag')?_('gender_flag'):0;
		$arguments['astro'] 		= 	member_util_setting::getAstro(_('month'), _('day'));
		$arguments['bloodtype'] 	= 	_('bloodtype');
		$arguments['marriage'] 		=	_('marriage');
        $arguments['cale_type']     =   _('cal_type')?_('cal_type'):1;
		$arguments['r_province'] 	= 	_('r_province');
		$arguments['r_city'] 		= 	_('r_city');
		$arguments['r_district'] 	= 	_('r_district');
		$arguments['h_province'] 	= 	_('h_province');
		$arguments['h_city'] 		= 	_('h_city');
		$arguments['h_district'] 	= 	_('h_district');
		$arguments['my_desc'] 		= 	_('my_desc');
		
		if (!$this->data->edit($arguments, $uid)) {
			friends_util_cache::getUserInfo($uid,true);
			$this->ret = self::failure(Error::ERROR_UNKNOWN );
			return ;
		}
		
		/**
		 *	更新文件缓存
		 */
		/*if ($userInfo = friends_util_cache::getUserInfo($uid)) {
			$userInfo = array_merge($userInfo, $arguments);
			MemRow::setCache(MemRow::genRowKey('friends', $uid), $userInfo);
		} else {
			MemRow::removeCache(MemRow::genRowKey('friends', $uid));
		}*/
		
		$this->ret = self::success($uid);
		$this->addMessage('基本资料已更新');
	}
	
	/**
	 * flash保存头像
	 */
	public function save_avatar_action(){
		$type = _('type')?_('type'):'small';
        $uid = _('photoId')?_('photoId'):self::$login['uid'];
        $uid = self::$login['uid'];
        $save_path = $this->avatar->get_avatar_path($uid,$type);
        /**
         * 上传文件
         */
        $len = file_put_contents($save_path,file_get_contents("php://input"));
        $this->avatar->data->urls[0] = CT_IMG_DOMAIN.'/avatar/'.$this->avatar->get_directory($uid).'/'.$this->avatar->get_filename($uid,$type);
        $this->avatar->status = 1;
        $this->avatar->statusText = '上传成功!';

        /**
         * 删除原始图片
         */
        if($type == 'small'){
            $ori_file = DOCUMENT_PATH.'/sns/temp/avatar/origin/avatar_'.$uid.'.jpg';
            file_put_contents(LOG_PATH.'/avatar.log',$ori_file ."\r\n",FILE_APPEND);
            if(file_exists($ori_file)){
                @unlink($ori_file);
            }
        }elseif($type == 'big'){
            /**
             * 生成中图
             */
//            cartoon_util_upload::setCuteConf(array('mid'=>array('width'=>120,'heigth'=>120)));
            $cute = new cartoon_util_resize($save_path);
            $new_file = $this->avatar->get_avatar_path($uid,'mid');
            $cute->setNewImage($new_file);
			$cute->setNewSize(120,120);
			$cute->make();
        }
        /**
         * 跟新头像信息
         */
        $this->data->up_headimg($uid,1);        
        $msg = json_encode($this->avatar);
        echo $msg;
        exit;
	}

    public function save_camera_action(){
        $uid = _('photoId')?_('photoId'):self::$login['uid'];
        $type = _('type')?_('type'):'small';
        $uid = self::$login['uid'];
        $save_path = $this->avatar->get_avatar_path($uid,$type);
        $len = file_put_contents($save_path,file_get_contents("php://input"));
        $this->avatar->data->urls[0] = CT_IMG_DOMAIN.'/avatar/'.$this->avatar->get_directory($uid).'/'.$this->avatar->get_filename($uid,$type);
        $this->avatar->status = 1;
        $this->avatar->statusText = '上传成功!';

        $msg = json_encode($this->avatar);
        echo $msg;
        exit;
    }

    public function test_action(){
        $rs = $this->avatar->get_avatar_path($uid,'samll');
        var_dump($rs);exit;
    }
	
	/**
	 * 上传头像文件
	 */
	public function save_photo_action() {
        $this->requireLogin();
        $uid = self::$login['uid'];
		if ($_FILES ['Filedata']) {
			$rs = $this->avatar->upload_photo ( $uid, 'Filedata' );
			file_put_contents(LOG_PATH.'/upload_photo.log',serialize($rs)."\r\n",FILE_APPEND);
			if ($rs ['result'] == true) {
				/**
				 * 图片上传成功
				 */
				echo '<script type="text/javascript">window.parent.hideLoading();window.parent.buildAvatarEditor("' . $uid . '","' . 'http://i.'.DOMAIN.'/temp/'.$rs['url'] . '","photo");</script>';
				exit ();
			} else {
				switch ($rs ['message']) {
					case cartoon_util_upload::ERROR_FILETYPE :
						$this->responseJs ( '图片类型错误,请上传JPEG类型的图片!', null, true );
						exit ();
					case cartoon_util_upload::ERROR_IMGSIZE :
						$this->responseJs ( '图片大小不符合规范！', null, true );
						exit ();
					default :
						$this->responseJs ( '图片上传失败，请重新上传', null, true );
						exit();
				}
			}
		}
		$this->view = 'avatar';
	}

	/**
	 * 验证用户名是否已经被使用
	 *
	 */
	public function chkname_action(){
		$username = _('username');		
		$this->_renderJson();		
		if(!$username or $uid = $this->data->getUserByName($username,array('uid'))){
			$this->ret = self::failure(ConstMembers::ERR_EXIST_USER);//用户名已存在
		}else{
			$this->ret = self::success();
		}
		
	}
	
	/**
	 * 获得分页列表
	 *
	 */
	public function att_list_action(){
		$uid = $this->getUid();
		$page = _('page',1);
		if($uid){
			$list = $this->data->getAttList($uid,$page,15);
			$pages = $this->genPages($list['INFO']);
			$this->ret = array('data'=>$list['ROWS'],'pages'=>$pages);
			$this->view = 'att_list';
//			$this->ret = self::success(Cache::cacheFunction(array($this->o, 'selectByPage'), array($uid, $this->page?intval($this->page):1, self::PAGESIZE ), false));
		}else{
			$this->requireLogin();
		}
	}
	
	/**
	 * 验证邮箱是否已经被使用
	 *
	 */
	public function chkemail_action(){
		$email = _('email');		
		$this->_renderJson();		
		if(!$email or $uid = $this->data->getUserByEmail($email,array('uid'))){
			$this->ret = self::failure(ConstMembers::ERR_EXIST_EMAL );//邮箱已存在
		}else{
			$this->ret = self::success();
		}
		
	}
	
	/**
	 * 发送邮件
	 *
	 */
	public function sendmail_action(){
		$tomail = 'fanzhanao@163.com';
		$subject = '发送一个邮件试试';
		$contents = '发送邮件测试一下，发送邮件测试一下';
		$rs = member_util_interface::sendMail($tomail,$subject,$contents);
		var_dump($rs);
		exit;
	}
    
}
